package com.dp.appi.dao.impl;

import com.dp.appi.dao.EncyclopediaDao;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xiaoji on 2016/4/28.
 */
@Component
public class EncyclopediaDaoImpl extends BaseDaoImpl implements EncyclopediaDao {
    /**
     * 获取百科分类
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> getCategory() {
        String sql="select category_id,name from e_category where deleted=0 and enable=1 ORDER BY sort ASC";
        return getJdbcTemplate().queryForList(sql);
    }

    /**
     * @param name 百科名称
     * @param s    开始序列
     * @param n    获取条数
     * @return
     */
    @Override
    public List<Map<String, Object>> encyclopediaList(String name,Integer category_id, Integer s, Integer n) {
        String sql="select encyclopedia_id,tsbu.realname as author,ee.title,ee.article_thumb,UNIX_TIMESTAMP(ee.create_time) as create_time " +
                " from e_encyclopedia ee" +
                " LEFT JOIN t_s_base_user tsbu on ee.author=tsbu.ID " +
                " where ee.deleted=0"+
                " and ee.category=?";
        if(!StringUtils.isEmpty(name)){
            sql +=" and ee.title like '%"+name+"%'";
        }
        sql+=" order by ee.create_time DESC limit ?,?";
        return getJdbcTemplate().queryForList(sql,new Object[]{category_id,s,n});
    }

    /**
     * 获取百科内容
     *
     * @param encyclopedia_id 百科id
     * @return
     */
    @Override
    public Map<String, Object> getEncyclopediaContent(String userId,Long encyclopedia_id) {
        String sql="select ee.encyclopedia_id,tsbu.realname as author,ee.title,ee.article_thumb,ee.content,ee.intro," +
                "UNIX_TIMESTAMP(ee.create_time) as create_time ,IF(efa.favorite_id is null,0,1) is_favorite,efa.favorite_id" +
                " from e_encyclopedia ee " +
                " LEFT JOIN t_s_base_user tsbu on ee.author=tsbu.ID " +
                " LEFT JOIN e_favorite efa on efa.encyclopedia_id = ee.encyclopedia_id and efa.user_id = ?"+
                " where ee.encyclopedia_id=? and ee.deleted=0 ";
        Map<String,Object> map = findOneObject(sql,new Object[]{userId,encyclopedia_id});
        if(map!=null){
            String sql2 = "select attachment_id,name,postfix,path from e_attachment where encyclopedia_id=?";
            List<Map<String,Object>> list = getJdbcTemplate().queryForList(sql2,new Object[]{encyclopedia_id});
            map.put("attachment",list);
            return map;
        }else{
            return new HashMap<>();
        }
    }
}
